import { Component, OnInit } from '@angular/core';
import { ModalController, NavController } from '@ionic/angular';
import { VideoModal } from '@modals/alarm-video/alarm-video';
import { PromptAlarmModal } from '@components/prompt-alarm/prompt-alarm';
import { Subscription } from 'rxjs';
import { MessageService } from '@services/message.service';

import { DataService } from '@services/data.service';

import { AlarmDetailPage } from '@components/alarm-detail/alarm-detail';
import { CacheService } from '@services/cache.service';
import { MyNoteService } from '@services/myNote.service';
import { providerDef } from '@angular/core/src/view';
import { Router } from '@angular/router';
import { forkJoin } from 'rxjs';
import { DatePipe } from '@angular/common';


@Component({
  selector: 'page-alarm',
  templateUrl: 'alarm.html',
  styleUrls: ['alarm.scss']
})
export class AlarmPage implements OnInit {
  userId;
  alarmArresultLength = 0; // 告警总数
  functionList; // tab列表
  state = 'alarm'; // 当前tab页
  alarmArresult = []; // 设备告警分段
  alarmDatas = [];  // 告警数据
  alarmDatasLen;    // 告警总数
  fireAlarms = [];  // 消防告警数据
  eventDatas = [];  // 事件数据
  pageIndex = 1;    // 默认页码
  pageSize = 30;
  alarmLevel = 1;
  totalSize = undefined;
  _refreshInterval;
  dealAlarmPermission = true;
  projectId;
  subscription: Subscription;
  taskState = ['', '已确认', '已到场', '已处理', '已完成', '已完成'];

  hasData = true;          // 是否有告警数据
  IsILastPage = false;  // 是否为最后一页
  constructor(
    private modalCtrl: ModalController,
    private dataService: DataService,
    private cache: CacheService,
    private myNote: MyNoteService,
    private messageService: MessageService,
    public navCtrl: NavController,
    public router: Router,
    public datePipe: DatePipe
  ) {
    this.userId = this.cache.userinfo.userId;
    this.subscription = this.messageService.getMessage().subscribe(data => {
      if (data.id === 'projectChange' && data.data) {
        console.log('项目改变', data);
        this.state = 'alarm';
        this.projectId = data.data.projectId;
        this.getAlarm(this.projectId);
        this.getFireParams(this.projectId, false, true);
        this.getEvent(this.projectId, null, null);
      }
    });
  }

  changeAlarmTab(data) {
    this.state = data;
    if (data === 'alarm') {
      this.pageIndex = 1;
      this.getAlarm(this.projectId);
    } else if (data === 'fireAlarm') {
      this.getFireParams(this.projectId, null, false);
    } else {
      this.pageIndex = 1;
      this.getEvent(this.projectId, null, null);
    }
  }

  ngOnInit() {
    this.state = 'alarm';
    this.functionList = [{ functionCode: 'alarm', functionName: '告警' }, { functionCode: 'event', functionName: '事件' }];
  }

  ionViewWillEnter() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements != null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'flex';
      });
    }
    this.state = 'alarm';
    this.pageIndex = 1;
    this.IsILastPage = false;
    this.projectId = this.cache.currentProject.projectId;
    this.getAlarm(this.projectId);
    this._refreshInterval = setInterval(() => {
      this.getAlarm(this.projectId);
    }, 10000);
    this.getFireParams(this.projectId, null, true);
  }

  ionViewWillLeave() {
    this.hasData = true;
    this.alarmDatas = this.fireAlarms = this.eventDatas = [];
    if (this._refreshInterval) {
      clearInterval(this._refreshInterval);
    }
  }

  // 获取设备告警
  getAlarm(projecId, refresher = null, infiniteScroll?) {
    // 实时告警
    const realTimeAlarm = this.dataService.getRealTimeAlarmList(projecId);
    // 历史告警
    const toDay = this.datePipe.transform(new Date(), 'yyyy-MM-dd 23:59:59');
    const days = + new Date() - 1000 * 60 * 60 * 24 * 2;
    const daysAgo = this.datePipe.transform(new Date(days), 'yyyy-MM-dd 00:00:00');
    const searchTime = [daysAgo, toDay];
    const restoreAlarm = this.dataService.getRestoreAlarmList(projecId, searchTime, this.pageIndex, this.pageSize);
    this.IsILastPage = false;
    forkJoin([realTimeAlarm, restoreAlarm]).subscribe((res) => {
      if (res.length > 0) {
        // 时间排序
        const realTimeAlarmList = this.getAlarmListSort(res[0].data || [], true, true);
        const restoreAlarmList = this.getAlarmListSort(res[1].data.datas || [], true, false);
        if (restoreAlarmList.length) {
          this.IsILastPage = false;
        }
        // 列表底部总长度
        this.alarmArresultLength = realTimeAlarmList.length + res[1].data.total;
        if (!this.alarmArresultLength) {
          this.hasData = false;
        } else {
          this.hasData = true;
        }

        // 历史告警全部已恢复
        restoreAlarmList.forEach(item => { item.isRestore = true; })

        if (typeof this.pageIndex !== 'number') {
          this.pageIndex = 1;
        }

        let alarmArr;
        if (this.pageIndex === 1) {
          alarmArr = [...realTimeAlarmList, ...restoreAlarmList];
          this.alarmDatas = this.getResultAlarmDatas(alarmArr);
        } else {
          Array.prototype.push.apply(this.alarmDatas, this.getResultAlarmDatas(restoreAlarmList));
        }
        if (infiniteScroll) {
          setTimeout(() => {
            infiniteScroll.complete();
            if (!restoreAlarmList.length) {
              this.IsILastPage = true;
            }
          }, 500);
        }
        if (refresher) {
          refresher.complete();
        }
      }
    })
  }

  // 告警排序
  getAlarmListSort(data, isTime = false, isState = false) {
    const untreatedArr = [], doingArr = [];
    if (isTime) {
      data.sort((a, b) => {
        return Date.parse(b.deviceValueLastTime || b.alarmTime) - Date.parse(a.deviceValueLastTime || a.alarmTime)
      })
    }
    if (isState) {
      data.forEach((item) => {
        if (item.procState === 0) {
          untreatedArr.push(item);
        } else {
          doingArr.push(item);
        }
      })
      data = [...untreatedArr, ...doingArr];
    }
    return data;
  }

  // 设备告警数据处理
  getResultAlarmDatas(arr) {
    if (arr) {
      arr.forEach((c) => {
        c.id = null;
        c.alarmTime = c.deviceValueLastTime || c.alarmTime;
        c.name = c.areaName + ' ' + c.deviceName;
        c.listType = c.isRestore ? '已恢复' : c.procState !== 0 ? '未恢复' : '未处理';
        c.alarmTypeName = c.alarmTypeName || c.alarmName;
        c.alarmReason = c.alarmValue + c.unit;
        c.type = 1;
        c.handleType = this.taskState[c.procState];
        c.restoreTime = c.recoveryTime
      });
      return arr;
    }
  }

  // 获取消防告警列表
  getFireParams(projectId, refresher, isChange) {
    this.dataService.getFireAlarms(projectId).subscribe(res => {
      this.dataService.getHistoryFireAlarms(projectId).subscribe(data => {
        const realTimeAlarm = res.data && res.data.realTimeInfos ? res.data.realTimeInfos : [];
        const historyTimeAlarm = data.data && data.data.historyInfos ? data.data.historyInfos : [];
        this.fireAlarms = realTimeAlarm.concat(historyTimeAlarm);
        if (isChange) {
          if (this.fireAlarms.length) {
            if (this.functionList[1].functionCode === 'fireAlarm') {
              return;
            } else {
              this.functionList.splice(1, 0, { functionCode: 'fireAlarm', functionName: '消防告警' });
            }
          } else {
            if (this.functionList[1].functionCode === 'fireAlarm') {
              this.functionList.splice(1, 1);
            } else {
              return;
            }
          }
        }
      });
      if (refresher) {
        refresher.complete();
      }
    });
  }

  // 获取事件
  getEvent(projecId, infiniteScroll, refresher) {
    // 默认加载第一页数据
    if (typeof this.pageIndex !== 'number') {
      this.pageIndex = 1;
    }

    this.dataService.projectEventList(projecId, this.pageIndex, this.pageSize).subscribe(val => {
      if (this.pageIndex === 1) {
        this.eventDatas = val.data.datas;
      } else {
        Array.prototype.push.apply(this.eventDatas, val.data.datas);
      }
      this.totalSize = val.data.total;
      if (infiniteScroll) {
        infiniteScroll.target.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    });
  }

  eventClick() {
    this.eventDatas = [];
    this.pageIndex = 0;
    this.totalSize = undefined; // 清除总页数记录，否则是否有数据判断可能直接为false
  }

  // 事件分页加载
  loadData(type, infiniteScroll, refresher) {
    this.pageIndex++;
    if (this.state === 'alarm') {
      this.getAlarm(this.projectId, refresher, infiniteScroll);
    } else {
      this.getEvent(this.projectId, infiniteScroll, refresher);
    }

  }

  // 下拉刷新
  doRefresh(refresher) {
    this.IsILastPage = false;
    if (this.state === 'alarm') {
      this.pageIndex = 1;
      this.getAlarm(this.projectId, refresher);
    } else if (this.state === 'fireAlarm') {
      this.getFireParams(this.projectId, refresher, true);
    } else if (this.state === 'event') {
      this.eventClick();
      this.pageIndex = 1;
    }
    setTimeout(() => {
      console.log('Async operation has ended');
      if (refresher) {
        refresher.complete();
      }
    }, 15000);
  }

  // 判断是否有更多的数据可以加载
  moreDataCanBeLoaded() {
    // 数据总数请求没有返回时，默认加载
    if (this.totalSize == null) {
      return true;
    }
    let bool = true;
    const pageTotal = Math.ceil(this.totalSize / this.pageSize);
    if (this.pageIndex >= pageTotal) {
      bool = false;
    }
    return bool;
  }


  async showPopup(data) {
    console.log(data);
    data.createUserId = data.lastUserId
    if (data.procState === 0 && !data.isRestore) {
      const modal = await this.modalCtrl.create({
        component: PromptAlarmModal,
        componentProps: {
          title: '告警处理'
        }
      });
      await modal.present();
      modal.onDidDismiss().then(choose => {
        if (choose.data === 1) {                             // 立即处理
          let reqBody;
          reqBody = {
            isLook: choose.data,
            ProcState: 1,
            DeviceId: data.deviceId,
            DeviceParameterId: data.deviceParameterId,
            AlarmTypeId: data.alarmTypeId
          };
          if (data.isRestore === true) {
            reqBody.AlarmId = data.alarmId;
          }
          this.makeDetailPage(data);
        } else if (choose.data === 0) {                      // 查看详情
          this.makeDetailPage(data, true);
        }
      });
    } else {
      this.makeDetailPage(data);
    }
  }

  makeDetailPage(data, isLook = false) {
    data.lastUserId = data.lastUserId === 0 ? this.userId : data.lastUserId;
    this.navCtrl.navigateForward(['tabs/alarm/AlarmDetailPage'], {
      queryParams: {
        data: data,
        alarmType: 'alarm',
        isLook: data.isRestore || this.userId !== data.lastUserId || isLook ? true : false, // 是否查看
        // isLook: data.isMy && data.lastCancelUserId !== this.userId && data.procState !== 4 ? false : true,
        url: 'tabs/alarm/AlarmDetailPage/AlarmSolveComponent', // 子级处理描述跳转url
        callback: () => {// 返回回调，更新列表状态
          this.getAlarm(this.projectId, null);
          this.getFireParams(this.projectId, null, true);
        }
      }
    });
  }
  async watchVideo(data) {
    console.log(data)
    const config = {
      title: data.areaName + ' ' + data.deviceName,
      message: data.alarmTypeName + data.alarmReason,
      preload: true,
      plugins: {
        poster: 'http://120.76.244.22:3000/android/1.5.9/poster.jpg'
      },
      sources: [{ src: data.urls[0], type: 'video/mp4', condition: Math.random() }]
    };

    const videoModal = await this.modalCtrl.create({
      component: VideoModal,
      componentProps: { config: config }
    });
    await videoModal.present();
  }

  eww() {
    alert();
  }
}
